let seeAlltalkID = '';   //点击查看按钮时  储存点击的评论ID  
let Replyid = '';  // 回复目标
let replyUser = ''; //回复人XXX
let replytype = '';//回复类型




//滑过评论控件  显示删除按钮
$('#talk_content').on('mouseover', '.ds_content', function () {
  if (Uid == $(this).attr('data-userid')) {

    $(this).find('#talk_remove').removeClass('none')
  }
});

//移出评论控件  隐藏删除按钮
$('#talk_content').on('mouseout', '.ds_content', function () {
  $(this).find('#talk_remove').addClass('none')
})



//滑过回复控件  显示删除
$('#talk_content').on('mouseover', '.one_reply ', function () {
  if (Uid == $(this).attr('data-touid')) {
    $(this).find('#reply_remove').removeClass('none')
  }
});
//移出回复控件  隐藏删除
$('#talk_content').on('mouseout', '.one_reply', function () {
  $(this).find('#reply_remove').addClass('none')
})

//对文章评论   ++++++++++++++++++++++
$('#textareaBox').on('focus', function () {
  $('#cancelbtn').removeClass('none')
})
//取消评论
$('#cancelbtn').on('click', function () {
  $('#textareaBox').val('')
  $(this).addClass('none')
})

//发布评论
$('#talk_submit').on('click', function () {
  //提交请求
  let content = $.trim($('#textareaBox').val())
  let loginapi = $("#comentsandreply").attr('data-login');
  let commentapi = $(this).parent().attr('data-commentapi');
  if (Uid === "0" || typeof (Uid) == "undefined") {
    alertTips("notice", "请先登录再操作", 2000, loginapi);
  } else if (content.length > 5 && content.length < 256) {

    let data = {
      content: content,
    };
    $.ajax({
      url: commentapi,
      type: "post",
      data: data,
      dataType: "json",
      success: (res) => {
        res = parseJson(res);
        if (res.errcode === 0) {
          $('#textareaBox').val('')
          $('#cancelbtn').addClass('none')
          getTalkData();
          alertTips("success", res.message, 2000, "");
          // emojirenderData();
        } else {
          alertTips("error", res.message, 3000, "");
        }
      },
      error: () => {
        alertTips("error", "系统错误！", 3000, "");
      }
    });
  } else {
    alertTips("error", '回复内容限 5 - 256 个字符容', 3000, "");
  }
})

//点击回复 
// 判断是否对自己回复  对自己回复则 return
// 判断是否存在评论框  不存在创建 同时设置文本域值 @xxxx ++++++++++++++++++++++
$('#talk_content').on('click', '.reply_fn', function () {

  if ($(this).attr('data-touid') == Uid) {
    alertTips("info", '不能自己回复自己', 2000, "");
    return;
  }
  let loginapi = $("#comentsandreply").attr('data-login');
  if (Uid === "0" || typeof (Uid) == "undefined") {
    alertTips("notice", "请先登录再操作", 2000, loginapi);
  }
  let areachild = $('#talk_content').find('.talk_box_s')

  if ($(areachild).length == 0) {
    let textBox = setchildTextarea();
    $(this).parent().parent().append(textBox)

  } else {

    $('#talk_content').find('.talk_box_s').remove();
    emojidel();
    let textBox = setchildTextarea();
    $(this).parent().parent().append(textBox)
  }

  let val = $(this).attr('data-username');
  $('#talk_content').find('#textareaBox_s').val('@' + val + ' ')
  replyUser = val;
  Replyid = $(this).attr('data-toid');
  Touid = $(this).attr('data-touid');
  replytype = $(this).attr('data-replytype');
  emojiini("#textareaBox_s");
})
//回复发布   
$('#talk_content').on('click', '#talk_submit_s', function () {
  // 替换 @ xxx 为空
  let content = ($.trim($('#textareaBox_s').val())).replace((replyUser), '')
  content = content.replace('@', '')
  let replyapi = $("#comentsandreply").attr('data-replyapi');
  let commentid = $(this).parents('.comment').attr('data-commentid')
  if (content.length > 5 && content.length < 256) {

    let data = {
      content: content,
      replyid: Replyid,
      commentid: commentid,
      replytype: replytype,
      touid: Touid,
    }
    $.ajax({
      url: replyapi,
      type: "post",
      data: data,
      dataType: "json",
      success: (res) => {
        res = parseJson(res);
        if (res.errcode === 0) {
          $(this).parents('.talk_box_s').remove();
          emojidel();
          getTalkData();

          alertTips("success", res.message, 2000, "");
          // emojirenderData();
        } else {
          alertTips("error", res.message, 3000, "");
        }
      },
      error: () => {
        alertTips("error", "系统错误！", 3000, "");
      }
    });
  } else {
    alertTips("error", '回复内容限 5 - 256 个字符容', 3000, "");
  }

})




//删除评论或回复
$('#talk_content').on('click', '#talk_remove', function () {

  let replyid = $(this).attr('data-id')
  let replytype = $(this).attr('data-type')
  let delapi = $("#comentsandreply").attr('data-delcommentapi');
  let data = {
    replyid: replyid,
    replytype: replytype,

  }
  $.ajax({
    url: delapi,
    type: "post",
    data: data,
    dataType: "json",
    success: (res) => {
      res = parseJson(res);
      if (res.errcode === 0) {
        $(this).parents('.talk_box_s').remove();
        emojidel();
        getTalkData();
        alertTips("success", res.message, 2000, "");
      } else {
        alertTips("error", res.message, 3000, "");
      }
    },
    error: () => {
      alertTips("error", "系统错误！", 3000, "");
    }
  });


})


//点击查看  获取评论并且根据talkID获取全部评论 
$('#talk_content').on('click', '#see_reply', function () {

  if ($(this).parents(".comment_people").siblings(".commentallreply").is(":hidden")) {
    $(this).parents(".comment_people").siblings(".commentallreply").slideDown();
    $(this).html("收起")
  } else {
    $(this).parents(".comment_people").siblings(".commentallreply").slideUp();
    $(this).html("查看")
  }
});

//回复取消
$('#talk_content').on('click', '#cancelbtn_s', function () {
  $(this).parents('.talk_box_s').remove();
  emojidel();
})

//回复评论框
function setchildTextarea() {
  return '<div class="talk_box talk_box_s">' +
    '<textarea name="talk" id="textareaBox_s" placeholder="写下你的评论..."></textarea>' +
    '<button id="talk_submit_s">发布</button><button id="cancelbtn_s" class="cancelbtn">取消</button></div>'
}

//对post或get进行封装，为了方便调试，后来没用
let commonfun = {
  request: (url, data, callback, failfun) => {
    $.ajax({
      url: url,
      type: "post",
      data: data,
      dataType: "json",
      success: (data) => {
        callback(data)
      },
      fail: (err) => {
        failfun(err)
      }
    })
  }
}

//emoji初始化
function emojiini(content) {
  $(content).emoji({
    showTab: true,
    animation: 'fade',
    icons: [{
      name: "QQ高清",
      path: "/static/jquery-emoji/img/qq/",
      maxNum: 91,
      file: ".gif",
      placeholder: "#qq_{alias}#"
    }, {
      name: "贴吧表情",
      path: "/static/jquery-emoji/img/tieba/",
      maxNum: 50,
      file: ".jpg",
      placeholder: ":{alias}:",
      alias: {
        1: "hehe",
        2: "haha",
        3: "tushe",
        4: "a",
        5: "ku",
        6: "lu",
        7: "kaixin",
        8: "han",
        9: "lei",
        10: "heixian",
        11: "bishi",
        12: "bugaoxing",
        13: "zhenbang",
        14: "qian",
        15: "yiwen",
        16: "yinxian",
        17: "tu",
        18: "yi",
        19: "weiqu",
        20: "huaxin",
        21: "hu",
        22: "xiaonian",
        23: "neng",
        24: "taikaixin",
        25: "huaji",
        26: "mianqiang",
        27: "kuanghan",
        28: "guai",
        29: "shuijiao",
        30: "jinku",
        31: "shengqi",
        32: "jinya",
        33: "pen",
        34: "aixin",
        35: "xinsui",
        36: "meigui",
        37: "liwu",
        38: "caihong",
        39: "xxyl",
        40: "taiyang",
        41: "qianbi",
        42: "dnegpao",
        43: "chabei",
        44: "dangao",
        45: "yinyue",
        46: "haha2",
        47: "shenli",
        48: "damuzhi",
        49: "ruo",
        50: "OK"
      },
      title: {
        1: "呵呵",
        2: "哈哈",
        3: "吐舌",
        4: "啊",
        5: "酷",
        6: "怒",
        7: "开心",
        8: "汗",
        9: "泪",
        10: "黑线",
        11: "鄙视",
        12: "不高兴",
        13: "真棒",
        14: "钱",
        15: "疑问",
        16: "阴脸",
        17: "吐",
        18: "咦",
        19: "委屈",
        20: "花心",
        21: "呼~",
        22: "笑脸",
        23: "冷",
        24: "太开心",
        25: "滑稽",
        26: "勉强",
        27: "狂汗",
        28: "乖",
        29: "睡觉",
        30: "惊哭",
        31: "生气",
        32: "惊讶",
        33: "喷",
        34: "爱心",
        35: "心碎",
        36: "玫瑰",
        37: "礼物",
        38: "彩虹",
        39: "星星月亮",
        40: "太阳",
        41: "钱币",
        42: "灯泡",
        43: "茶杯",
        44: "蛋糕",
        45: "音乐",
        46: "haha",
        47: "胜利",
        48: "大拇指",
        49: "弱",
        50: "OK"
      }
    }, {
      name: "emoji高清",
      path: "/static/jquery-emoji/img/emoji/",
      maxNum: 84,
      file: ".png",
      placeholder: "#emoji_{alias}#"
    }]
  });
}

//emoji del
function emojidel() {
  $(".emoji_btn").remove();
  $(".emoji_container").remove();
  emojiini("#textareaBox");
}

function emojirenderData() {
  $(".ds_content").emojiParse({
    icons: [{
      path: "/static/jquery-emoji/img/tieba/",
      file: ".jpg",
      placeholder: ":{alias}:",
      alias: {
        1: "hehe",
        2: "haha",
        3: "tushe",
        4: "a",
        5: "ku",
        6: "lu",
        7: "kaixin",
        8: "han",
        9: "lei",
        10: "heixian",
        11: "bishi",
        12: "bugaoxing",
        13: "zhenbang",
        14: "qian",
        15: "yiwen",
        16: "yinxian",
        17: "tu",
        18: "yi",
        19: "weiqu",
        20: "huaxin",
        21: "hu",
        22: "xiaonian",
        23: "neng",
        24: "taikaixin",
        25: "huaji",
        26: "mianqiang",
        27: "kuanghan",
        28: "guai",
        29: "shuijiao",
        30: "jinku",
        31: "shengqi",
        32: "jinya",
        33: "pen",
        34: "aixin",
        35: "xinsui",
        36: "meigui",
        37: "liwu",
        38: "caihong",
        39: "xxyl",
        40: "taiyang",
        41: "qianbi",
        42: "dnegpao",
        43: "chabei",
        44: "dangao",
        45: "yinyue",
        46: "haha2",
        47: "shenli",
        48: "damuzhi",
        49: "ruo",
        50: "OK"
      }
    }, {
      path: "/static/jquery-emoji/img/qq/",
      file: ".gif",
      placeholder: "#qq_{alias}#"
    }, {
      name: "emoji高清",
      path: "/static/jquery-emoji/img/emoji/",
      file: ".png",
      placeholder: "#emoji_{alias}#"
    }]
  });
}

function renderData(res) {

  if (res && res.length > 0) {
    let talkStr = '';  //整个评论信息
    res.forEach((talkitem, index) => {
      let replyStr = '';  //回复文本
      if (talkitem.replycommentsresult && talkitem.replycommentsresult.length > 0) {
        replyStr = `<div class="commentallreply" style="display: none;">`
        talkitem.replycommentsresult.forEach((item, index) => {
          //渲染评论数据
          replyStr +=
            ` <div data-id="` + item.id + `" data-userID="` + item.fromuid + `" class="one_reply ` + (index == talkitem.replycommentsresult.length - 1 ? 'one_reply_noborder' : '') + `">` +
            `<div class="comment_people_info ds-avatar ">` +
            `<img class="fl_left img-thumbnail img-circle img-responsive" src="` + item.fromavatar + `" alt="">` +
            `<span class="first_reply fl_left">` +
            `<a target="_blank" href=/user/` + item.fromaccount + `>` +
            `<span class="first_reply_aa">` + item.fromname + `</span>` +
            `</a>` +
            `<span class="first_reply_text"> 回复: </span>` +
            ` <a target="_blank" href=/user/` + item.toaccount + `>` +
            ` <span class="first_reply_aa">` + item.toname + `</span>` +
            `</a>` +
            ` </span>` +
            ` <span class="date fl_right">` + dateformat(item.created_at) + `</span>` +
            `</div>` +
            `<div data-userid="` + item.fromuid + `" date-deltype="reply" class="comment_people_content ds_content">` +
            ` <span class="fl_left">` + item.content + `</span>` +
            `<span data-touid="` + item.fromuid + `" data-toid="` + item.id + `" data-userName="` + item.fromname + `" data-replytype="reply" class=" reply_fn reply_btn fl_right">回复</span>` +
            ` <span id="talk_remove" data-id="` + item.id + `" data-type="reply" class="reply_remove reply_btn fl_right reply_btn_cont none">删除</span>` +
            `<span class="floor">` + index + `楼</span>` +
            ` </div>` +
            `</div>`
        });
        replyStr += `</div>`
      }
      talkStr +=
        `<li class="clearfix">` +
        `<div class="talk_content">` +
        `<div data-commentid="` + talkitem.id + `" data-userID="` + talkitem.uid + `" class="comment ">` +
        ` <div class="comment_people  ">` +
        ` <div class="comment_people_titleBox">` +
        `<div class="comment_people_info ds-avatar">` +
        ` <img src="` + talkitem.avatar + `"  class=" fl_left img-thumbnail img-circle img-responsive"   alt="` + talkitem.nickname + `">` +
        `<a target="_blank"  href=/user/` + talkitem.account + `>` +
        ` <span class="username">` + talkitem.nickname + `</span>` +
        ` </a>` +
        `<span>评分:<i class="bookstack-star star-` + talkitem.score + `"></i></span>` +
        `<span  class="date fl_left text-muted hidden-xs pull-right">` + dateformat(talkitem.created_at) + `</span>` +
        `</div>` +
        `<div data-userid="` + talkitem.uid + `" date-deltype="comment"  class="comment_people_content ds_content">` +
        `<span class="fl_left">` + talkitem.content + `</span>` +
        (talkitem.replycommentsresult && talkitem.replycommentsresult.length > 0 ? `<span id="see_reply" class="see">查看</span>` : '') +
        `<span data-touid="` + talkitem.uid + `" data-toid="` + talkitem.id + `"
        data-userName="`+ talkitem.nickname + `" data-replytype="comment"
        class="reply_fn fl_right reply_btn ">回复(`+ (talkitem.replycommentsresult ? talkitem.replycommentsresult.length : 0) + `)</span>` +
        `<span id="talk_remove" data-id="` + talkitem.id + `" data-type="comment"
        class="reply_btn fl_right none reply_btn_cont">删除</span>`+
        `<span class="floor">` + index + `楼</span>` +
        `</div>` +
        `</div>` +
        `</div>` +
        replyStr +
        `</div>` +
        `</div>` +
        `</li>`

    });
    talkStr = `<ul>` + talkStr + `</ul>`
    $('#talk_content').html(talkStr);
    emojirenderData();
  }

}
//刷新评论区域
function getTalkData() {
  let data = {
    status: 1,
  }
  $.get(getreplyapi, data, renderData);
}
//格式化时间日期
function dateformat(date) {

  var date = new Date(+new Date(date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
  return date

}
